package iterator;

import global.AttrType;
import global.Vector100Dtype;
import heap.FieldNumberOutOfBoundException;
import heap.InvalidTupleSizeException;
import heap.InvalidTypeException;
import heap.Tuple;

import java.io.IOException;

import bufmgr.PageNotReadException;

/*
 * Class that scans through a file and returns the vectors that are within
 * a certain range, without using an index
 */

public class RangeVectorScan extends FileScan {
	
	public Vector100Dtype target;
	public int distance;
	public int fieldNumber;
	
	public RangeVectorScan(String  file_name,
			AttrType in1[],                
			short s1_sizes[], 
			short     len_in1,              
			int n_out_flds,
			FldSpec[] proj_list,
			CondExpr[]  outFilter,
			int fieldNumber,
			Vector100Dtype target,
			int distance
			) throws FileScanException, TupleUtilsException, InvalidRelation, IOException
	{
		super(file_name, in1, s1_sizes, len_in1, n_out_flds, proj_list, outFilter);
		this.target = target;
		this.fieldNumber = fieldNumber;
		this.distance = distance;
	}
	
	/*
	 * Only returns the index if the vector is within the specified range of the target vector
	 * @see iterator.FileScan#get_next()
	 */

	@Override
	public Tuple get_next() throws IOException, JoinsException, InvalidTupleSizeException, InvalidTypeException,
			PageNotReadException, PredEvalException,
			UnknowAttrType, FieldNumberOutOfBoundException, WrongPermat {
		Tuple tuple = super.get_next();
		while (tuple != null) {
			Vector100Dtype vector = tuple.get100DVectFld(this.fieldNumber);
			double vectorDistance = Vector100Dtype.Distance(this.target, vector);
			if ((int)vectorDistance <= this.distance) {
				return tuple;
			}
			tuple = super.get_next();
		}
		return tuple;
	}

	@Override
	public void close() {
		// Do nothing
	}

}
